import dayjs from 'dayjs'
import { defineStore } from 'pinia'
import { useAppStore } from './app.js'


const uniStorage = {
  setItem (key, state) {
     return  uni.setStorageSync(key,state) //Cookies.set('accessToken', state.accessToken, { expires: 3 })
  },
  getItem (key) {
	  return uni.getStorageSync(key)
  }
}

export const useUserStore = defineStore('user',{
	state:()=>{
		return {
			code:null,
			token:null,
			baseInfo:{
				head_icon_url: '',
				nickname:'',
				name:''
			},
			
		}
	},
	getters:{
		isLogin() {
			return !!this.token
		}
	},
	actions:{
		async wxlogin(){
			//#ifdef MP-WEIXIN
			
			let appStore = useAppStore()

			if(!this.token)
			{
				let that = this
				uni.showLoading({
					title:'微信登录'
				})
				
				let result = await new Promise((resolve,reject)=>{
					uni.login({
						provider:'weixin',
						success(res) {
							console.log(res)
							that.code = res.code
							appStore.http.get(`/common/account/wxlogin?code=${res.code}`)
							.then((res)=>{
								console.log(res)
								that.token = res.data.token
								that.baseInfo = res.data.user
								
								resolve(true)
							}).catch((err)=>{
								reject(err)
							})
						},
						fail() {
							reject(false)
						}
					})
				})
				
				uni.showLoading({
					title:'正在支付'
				})
				
				//let res = await this.pay()
				
				uni.hideLoading()
				
				return result
			}
			//#endif
		},
		async pay(){
			//订单对象，从服务器获取
			var orderInfo = {
			  "appid": "wx7075f04edc923e5b",  // 应用ID（AppID）
			  "partnerid": "1558656881",      // 商户号（PartnerID）
			  "prepayid": "wx12213650009312a57c534577d207d60000", // 预支付交易会话ID
			  "package": "Sign=WXPay",        // 固定值
			  "noncestr": "QvbFz1G43aTXNKB9", // 随机字符串
			  "timestamp": dayjs().unix(),        // 时间戳（单位：秒）
			  "sign": "00378059A9646682CC16EA5F3A6FED3B" // 签名，这里用的 MD5 签名
			};
			
			const paramters = {
				signType:'MD5',
				nonceStr:'ZRpjpjzzPRCyTWQErY2yBe6r58dxiTrJ',
				package:'prepay_id=wx1301525283381221bd4b8a75aa70d90000',
				paySign:'C000DB4113F89D01252E906C27428CBC',
				timeStamp:'1697133172'
			}
			
			
			// nonceStr:
			// 'ZRpjpjzzPRCyTWQErY2yBe6r58dxiTrJ'
			// package:
			// 'prepay_id=wx1301525283381221bd4b8a75aa70d90000'
			// paySign:
			// 'C000DB4113F89D01252E906C27428CBC'
			// signType:
			// 'MD5'
			// timeStamp:
			// '1697133172'
			
			console.log(paramters)
			
			const result = await new Promise((resolve,reject)=>{
				uni.requestPayment({
				    provider: 'wxpay',
					...paramters,
					success: function (res) {
						console.log('success:' + JSON.stringify(res));
						console.log("支付成功");
						resolve(res)
					},
					fail: function (err) {
						console.log('fail:' + JSON.stringify(err));
						console.log('支付失败:' + JSON.stringify(err));
						reject(err)
					}
				});
				
				// uni.getProvider({
				//     service: 'payment',
				//     success: function (res) {
				//         console.log(res.provider)
				//         if (~res.provider.indexOf('wxpay')) {
				//             uni.requestPayment({
				//                 "provider": "wxpay",  //固定值为"wxpay"
				//                 //"orderInfo": orderInfo, //非微信小程序
				// 				...paramters,
				//                 success: function (res) {
				//                     var rawdata = JSON.parse(res.rawdata);
				//                     console.log("支付成功");
				// 					resolve(rawdata)
				//                 },
				//                 fail: function (err) {
				//                     console.log('支付失败:' + JSON.stringify(err));
				// 					reject(err)
				//                 }
				//             });
				//         }
				//     }
				// });
			})
			
			console.log(result)
			return result
		}
	},
	// persist: {
	//     enabled: true,
	//     strategies: [
	// 		{
	// 			key: 'user',
	// 			storage:uniStorage
	// 		}
	// 	]
	// }
})